//从上到下打印出二叉树的每个节点，同一层的节点按照从左到右的顺序打印。 
//
// 
//
// 例如: 给定二叉树: [3,9,20,null,null,15,7], 
//
//     3
//   / \
//  9  20
//    /  \
//   15   7
// 
//
// 返回： 
//
// [3,9,20,15,7]
// 
//
// 
//
// 提示： 
//
// 
// 节点总数 <= 1000 
// 
//
// Related Topics 树 广度优先搜索 二叉树 👍 266 👎 0


package leetcode.editor.cn;

// [剑指 Offer 32 - I]从上到下打印二叉树

import java.util.ArrayList;
import java.util.LinkedList;

public class CongShangDaoXiaDaYinErChaShuLcof_JianZhiOffer32I {
    public static void main(String[] args) {
        Solution solution = new CongShangDaoXiaDaYinErChaShuLcof_JianZhiOffer32I().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int[] levelOrder(TreeNode root) {
            if (root == null) return new int[0];
            ArrayList<Integer> list = new ArrayList<>();
            LinkedList<TreeNode> treeNodes = new LinkedList<>();
            TreeNode cur = root;
            treeNodes.add(cur);
            while (!treeNodes.isEmpty()) {
                cur = treeNodes.poll();
                list.add(cur.val);
                if (cur.left != null)
                    treeNodes.add(cur.left);
                if (cur.right != null)
                    treeNodes.add(cur.right);
            }
            int[] ans = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ans[i] = list.get(i);
            }
            return ans;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

}